<template>
  <div class="app-content">
    <div class="content-header">
      <Row class="header-operations">
        <Col>
          <Button type="primary" class="mr-15" @click="add(1)" v-if="overallAdd"
            >总体辨识</Button
          >
          <Button type="primary" class="mr-15" @click="add(2)" v-if="dynamicAdd"
            >动态辨识</Button
          >
        </Col>
      </Row>
      <Row class="header-query" type="flex">
        <Col span="5">
          <Select v-model="searchModel.projectId" placeholder="项目名称">
            <Option v-for="item in projects" :value="item.id" :key="item.id">{{
              item.shortName
            }}</Option>
          </Select>
        </Col>
        <Col span="5" offset="1">
          <Input
            v-model="searchModel.constructionPointName"
            placeholder="工点名称"
            clearable
          />
        </Col>
        <Col span="5" offset="1">
          <Select
            v-model="searchModel.riskCategoryId"
            placeholder="作业风险类别"
            clearable
          >
            <Option
              v-for="item in riskCategories"
              :value="item.id"
              :key="item.id"
              >{{ item.riskCategoryName }}</Option
            >
          </Select>
        </Col>
      </Row>
      <Row class="header-query" type="flex">
        <Col span="5">
          <Select
            v-model="searchModel.riskLevel"
            placeholder="作业风险等级"
            clearable
          >
            <Option
              v-for="item in riskLevels"
              :value="item.value"
              :key="item.value"
              >{{ item.text }}</Option
            >
          </Select>
        </Col>
        <Col span="5" offset="1">
          <Select v-model="searchModel.stage" placeholder="状态" clearable>
            <Option
              v-for="item in stages"
              :value="item.value"
              :key="item.value"
              >{{ item.text }}</Option
            >
          </Select>
        </Col>
        <Col offset="11" span="2" style="text-align: right;">
          <Button type="primary" @click="queryList(1, 10)" v-if="query"
            >查询</Button
          >
        </Col>
      </Row>
    </div>
    <div class="content-body">
      <Table
        class="table"
        id="list-table"
        ref="listTable"
        border
        :columns="columns"
        :data="list"
        no-data-text="暂无数据"
        @on-selection-change="selectChange"
      >
        <template slot-scope="{ row }" slot="step">
          <span
            :class="{
              'step--blue': 1 === row.step,
              'step--yellow': 2 === row.step || 4 === row.step,
              'step--light-yellow': 3 === row.step,
              'step--red': 5 === row.step,
              'step--green': 6 === row.step
            }"
            >{{ row.stageName }}</span
          >
        </template>
        <template slot-scope="{ row }" slot="operation">
          <a v-if="4 === row.stage && revise" @click="initRevise(row.id)"
            >修订</a
          >
          <a v-if="1 === row.stage && dynamicEdit" @click="initControl(row.id)"
            >动态辨识</a
          >
          <a v-if="5 === row.stage && edit" @click="initSingleEdit(row.id)"
            >编辑</a
          >
          <a @click="initDetail(row.id)">详情</a>
          <a v-if="5 === row.stage && remove" @click="initRemove(row.id)"
            >删除</a
          >
        </template>
      </Table>
      <Row type="flex" justify="center">
        <Col>
          <Page
            class="pagination"
            :total="page.totalRecord"
            :current="page.currentPage"
            :page-size="page.pageSize"
            :pageSizeOpts="pageSizeOpts"
            @on-change="pageChange"
            @on-page-size-change="pageSizeChange"
            show-elevator
            show-total
            show-sizer
          />
        </Col>
      </Row>
    </div>
    <Modal
      v-model="isInquiries"
      title="业务问询"
      width="50%"
      ok-text="提交"
      :footer-hide="true"
    >
      <div class="modal-content">
        <inquiries
          ref="isInquiriesBox"
          :checkedRows="checkedRows"
          :businessType="businessType"
          @modelBox="modelBox"
          @person="person"
        ></inquiries>
      </div>
    </Modal>
    <Modal
      v-model="personModel"
      title="选择人"
      width="80%"
      ok-text="提交"
      :footer-hide="true"
    >
      <div class="modal-content">
        <checkPerson @personBox="personBox"></checkPerson>
      </div>
    </Modal>
    <span class="inquiries" @click="replyChild()">问询</span>
  </div>
</template>
<script>
import inquiries from '../../components/modules/inquiries/index'
import checkPerson from '../../components/modules/inquiries/checkPerson'
export default {
  components: {
    inquiries,
    checkPerson
  },
  name: 'risk-identification',
  data() {
    return {
      businessType: 'businesstype_identification',
      isInquiries: false,
      personModel: false,
      searchModel: {
        projectId: '',
        constructionPointName: '',
        riskCategoryId: '',
        riskLevel: 0,
        stage: 0
      },
      page: {
        currentPage: 1,
        pageSize: 10,
        totalRecord: 0
      },
      pageSizeOpts: [10, 20, 50, 100],
      projects: [],
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center',
          className: 'table--selection'
        },
        {
          width: 70,
          align: 'center',
          title: '序号',
          render: (h, params) => {
            return h(
              'span',
              this.page.pageSize * (this.page.currentPage - 1) +
                params.index +
                1
            )
          }
        },
        {
          title: '项目名称',
          key: 'projectName',
          align: 'center',
          tooltip: true
        },
        {
          title: '工点名称',
          key: 'constructionPointName',
          align: 'center',
          tooltip: true
        },
        {
          title: '是否在施',
          key: 'isWork',
          align: 'center'
        },
        {
          title: '作业风险类别',
          key: 'riskCategoryNames',
          align: 'center',
          tooltip: true
        },
        {
          title: '作业风险名称',
          key: 'riskName',
          align: 'center',
          tooltip: true
        },
        {
          title: '作业风险等级',
          key: 'riskLevelName',
          align: 'center'
        },
        {
          title: '状态',
          key: 'stageName',
          align: 'center',
          slot: 'step'
        },
        {
          title: '操作',
          slot: 'operation',
          align: 'center',
          className: 'table--operation'
        }
      ],
      list: [],
      checkedRows: [],
      riskCategories: [],
      // 风险等级
      riskLevels: [
        { text: 'I级', value: 1 },
        { text: 'II级', value: 2 },
        { text: 'III级', value: 3 },
        { text: 'IV级', value: 4 }
      ],
      // 状态
      stages: [
        { text: '待确认', value: 1 },
        { text: '项目待审', value: 2 },
        { text: '公司待审', value: 3 },
        { text: '集团待审', value: 4 },
        { text: '审核驳回', value: 5 },
        { text: '已通过', value: 6 }
      ],
      // 权限
      dispatch: false,
      currentUser: {},
      codes: [],
      isProjectPerson: false
    }
  },
  computed: {
    overallAdd() {
      const temp =
        this.codes.includes('P_0701_01') &&
        this.dispatch &&
        this.isProjectPerson &&
        this.currentUser.projectId === this.searchModel.projectId
      return temp
    },
    dynamicAdd() {
      const temp =
        this.codes.includes('P_0701_02') &&
        this.dispatch &&
        this.isProjectPerson &&
        this.currentUser.projectId === this.searchModel.projectId
      return temp
    },
    query() {
      return this.codes.includes('P_0701_04')
    },
    edit() {
      const temp =
        this.codes.includes('P_0701_05') &&
        this.dispatch &&
        this.isProjectPerson &&
        this.currentUser.projectId === this.searchModel.projectId
      return temp
    },
    remove() {
      const temp =
        this.codes.includes('P_0701_07') &&
        this.dispatch &&
        this.isProjectPerson &&
        this.currentUser.projectId === this.searchModel.projectId
      return temp
    },
    detail() {
      return this.codes.includes('P_0701_06')
    },
    revise() {
      const temp =
        this.codes.includes('P_0701_08') &&
        this.dispatch &&
        this.isProjectPerson &&
        this.currentUser.projectId === this.searchModel.projectId
      return temp
    },
    dynamicEdit() {
      const temp =
        this.codes.includes('P_0701_09') &&
        this.dispatch &&
        this.isProjectPerson &&
        this.currentUser.projectId === this.searchModel.projectId
      return temp
    }
  },
  methods: {
    // 问询弹框
    replyChild() {
      if (this.checkedRows.length > 5) {
        this.$Message.warning('最多可选5条风险进行批量问询')
        return
      } else if (this.checkedRows.length == 0) {
        this.$Message.warning('请先选择需要问询的风险')
        return
      } else {
        let isM = true,
          self = this
        try {
          self.checkedRows.forEach((e, index) => {
            if (index > 0) {
              if (e.projectId != self.checkedRows[index - 1].projectId) {
                this.$Message.warning('仅能选择同一项目下的风险询问')
                isM = false
                throw Error()
              }
            }
          })
        } catch (e) {}
        if (isM) {
          this.isInquiries = true
          this.$refs.isInquiriesBox.isModel()
        }
      }
    },
    // 关闭问询框
    modelBox() {
      this.isInquiries = false
    },
    // 打开人员选择框
    person() {
      this.personModel = true
    },
    // 关闭人员选择框
    personBox() {
      this.personModel = false
    },
    init() {
      this.$api.riskIdentification.judgeDispatch().then(({ code }) => {
        this.dispatch = 200 === code
        this.initData()
      })
    },
    initData() {
      const tempUser = localStorage.getItem('userList')
      if (tempUser) this.currentUser = JSON.parse(tempUser)
      const buttons = JSON.parse(localStorage.getItem('buttonList')) || []
      this.isProjectPerson = 3 == localStorage.getItem('personType')
      const routeName = this.$route.name
      const routeButtons = buttons.find(
        b => routeName === Object.keys(b).join('')
      )
      this.codes = routeButtons[routeName].map(b => b.code)
    },
    initProjects() {
      if (this.searchModel.projectId) {
        this.queryList()
      } else {
        this.$api.riskIdentification.queryProjectsForBusiness().then(res => {
          if (res.code === 200) {
            this.projects = res.data
            this.searchModel.projectId = this.projects[0].id
            this.queryList()
          } else {
            this.$Message.warning(res.message)
          }
        })
      }
    },
    // 获取风险类型
    initRiskCategories() {
      this.$api.measuresLibrary
        .getRiskCategoryFindAll()
        .then(({ code, data }) => {
          if (code === 200) {
            this.riskCategories = data
          }
        })
    },
    queryList(currentPage = 1, pageSize = 10) {
      this.page.currentPage = currentPage
      this.page.pageSize = pageSize
      this.checkedRows = []
      const param = {
        currentPage,
        pageSize,
        whereMap: {
          ...this.searchModel
        }
      }
      this.$api.riskIdentification
        .queryList(param)
        .then(({ code, data, message }) => {
          if (200 === code) {
            this.list = data.resultObject
            this.page.totalRecord = data.totalRecord
          } else {
            this.$Message.error(message)
          }
        })
    },
    pageChange(page) {
      this.queryList(page, this.page.pageSize)
    },
    pageSizeChange(size) {
      this.queryList(this.page.currentPage, size)
    },
    add(type) {
      this.$router.push({
        name: 'risk-identification-add',
        params: {
          type,
          project: this.searchModel.projectId
        }
      })
    },
    initSingleEdit(id) {
      this.$router.push({
        name: 'risk-identification-edit',
        params: {
          id
        }
      })
    },
    initDetail(id) {
      this.$router.push({
        name: 'risk-identification-detail',
        params: {
          id
        }
      })
    },
    initRevise(id) {
      this.$router.push({
        name: 'risk-identification-revise-edit',
        params: {
          id
        }
      })
    },
    initControl(id) {
      this.$router.push({
        name: 'risk-identification-control-edit',
        params: {
          id
        }
      })
    },
    selectChange(selection) {
      this.checkedRows = selection
    },
    initRemove(id) {
      this.$Modal.confirm({
        title: '删除提示',
        content: '<p>确认删除当前项吗？</p>',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          this.$api.riskIdentification.remove(id).then(({ code, message }) => {
            200 === code
              ? this.$Message.success('删除成功')
              : this.$Message.error(message)
            this.queryList()
          })
        }
      })
    }
  },
  mounted() {
    this.init()
    this.initRiskCategories()
    this.initProjects()
  },
  activated() {
    this.initProjects()
  }
}
</script>

<style lang="scss" scoped>
.app-content {
  .content-body {
    #list-table /deep/ .ivu-table .ivu-table-header .ivu-checkbox {
      display: none;
      cursor: none;
    }
  }
  .step--blue {
    color: #3170c8;
  }
  .step--yellow {
    color: #e7af63;
  }
  .step--light-yellow {
    color: #e7af64;
  }
  .step--red {
    color: #e32530;
  }
  .step--green {
    color: #3bbb0a;
  }
}
</style>
